import {defineStore} from 'pinia'
import {onMounted, onUnmounted, ref} from 'vue'
import cardConfig from '../config/cards.json'
import {message} from 'ant-design-vue'
import {useI18n} from 'vue-i18n'

export const useGameStore = defineStore('game', () => {
    // 国际化
    const {t} = useI18n()
    // 玩家数据
    const playerData = ref({
        cards: [],
        safeBox: [],
        gold: 100,
        drawCount: 16,
        lastDrawTime: Date.now(),
        collections: {},
        logs: []
    })
    // 市场卡片列表
    const marketCards = ref([])
    // 抽卡结果
    const newCard = ref(null)
    // 一键抽卡结果
    const newCards = ref([])
    // 交换箱卡片数量上限
    const CARD_LIMIT = 18
    // 保险箱卡片数量上限
    const SAFE_BOX_LIMIT = 50
    //
    const DRAW_RECOVERY_INTERVAL = 2 * 60 * 1000
    // 抽卡次数恢复定时器
    let drawRecoveryTimer = null

    onMounted(() => {
        // 加载数据
        loadData()
        // 每1秒增加一张抽卡次数
        drawRecoveryTimer = setInterval(updateDrawCount, 1000)
    })

    onUnmounted(() => {
        if (drawRecoveryTimer) {
            clearInterval(drawRecoveryTimer)
            drawRecoveryTimer = null
        }
    })

    // 增加可抽卡数量
    const updateDrawCount = () => {
        const now = Date.now()
        const timeElapsed = now - playerData.value.lastDrawTime
        const recoveries = Math.floor(timeElapsed / DRAW_RECOVERY_INTERVAL)
        if (recoveries > 0 && playerData.value.drawCount < 16) {
            playerData.value.drawCount = Math.min(16, playerData.value.drawCount + recoveries)
            playerData.value.lastDrawTime = now - (timeElapsed % DRAW_RECOVERY_INTERVAL)
            saveData()
        }
    }

    // 添加日志
    const addLog = (type, data) => {
        const timestamp = new Date().toLocaleString()
        let logMessage = ''
        if (type === 'draw') {
            logMessage = t('drawLog', {card: cardConfig.cards[data].name})
        } else if (type === 'setComplete') {
            logMessage = t('setCompleteLog', {set: cardConfig.sets[data].name})
        }
        playerData.value.logs.unshift({timestamp, message: logMessage})
        if (playerData.value.logs.length > 100) playerData.value.logs.pop()
        saveData()
    }

    // 加载存档
    const loadData = () => {
        try {
            const saved = localStorage.getItem('playerData')
            if (saved) {
                const parsedData = JSON.parse(saved)
                playerData.value = {
                    ...parsedData,
                    cards: Array.isArray(parsedData.cards) ? parsedData.cards : [],
                    safeBox: Array.isArray(parsedData.safeBox) ? parsedData.safeBox : [],
                    logs: Array.isArray(parsedData.logs) ? parsedData.logs : []
                }
            }
        } catch (e) {
            console.error('加载存档失败:', e)
            playerData.value.cards = []
            playerData.value.safeBox = []
            playerData.value.logs = []
        }
    }

    // 保存存档
    const saveData = () => {
        try {
            localStorage.setItem('playerData', JSON.stringify(playerData.value))
        } catch (e) {
            console.error('保存存档失败:', e)
        }
    }

    // 导出存档
    const exportData = () => JSON.stringify(playerData.value)

    // 导入存档
    const importData = (data) => {
        try {
            const parsedData = JSON.parse(data)
            playerData.value = {
                ...parsedData,
                cards: Array.isArray(parsedData.cards) ? parsedData.cards : [],
                safeBox: Array.isArray(parsedData.safeBox) ? parsedData.safeBox : [],
                logs: Array.isArray(parsedData.logs) ? parsedData.logs : []
            }
            saveData()
        } catch (e) {
            message.error(t('invalidSaveData'))
        }
    }

    // 是否可添加卡片
    const canAddCard = () => {
        return playerData.value.cards.length < CARD_LIMIT || playerData.value.safeBox.length < SAFE_BOX_LIMIT
    }

    // 添加卡片
    const addCard = (cardId) => {
        if (playerData.value.cards.length < CARD_LIMIT) {
            playerData.value.cards.push(cardId)
        } else if (playerData.value.safeBox.length < SAFE_BOX_LIMIT) {
            playerData.value.safeBox.push(cardId)
        } else {
            message.error(t('bothBoxesFull'))
            return false
        }
        saveData()
        return true
    }

    // 抽卡
    const drawCard = () => {
        updateDrawCount()
        if (playerData.value.drawCount <= 0) {
            return null
        }
        if (!canAddCard()) {
            return null
        }

        const cardId = getRandomCard()
        if (cardId && addCard(cardId)) {
            playerData.value.drawCount--
            newCard.value = cardId
            addLog('draw', cardId)
        }
        return cardId
    }

    // 一键抽卡
    const drawMultipleCards = () => {
        updateDrawCount()
        const availableDraws = playerData.value.drawCount
        const freeSlots = (CARD_LIMIT - playerData.value.cards.length) + (SAFE_BOX_LIMIT - playerData.value.safeBox.length)
        const drawCount = Math.min(availableDraws, freeSlots)

        if (drawCount <= 0) {
            message.error(availableDraws <= 0 ? t('noDrawCount') : t('bothBoxesFull'))
            return []
        }

        const drawnCards = []
        for (let i = 0; i < drawCount; i++) {
            const cardId = getRandomCard()
            if (cardId && addCard(cardId)) {
                drawnCards.push(cardId)
                playerData.value.drawCount--
                addLog('draw', cardId)
            } else {
                break
            }
        }
        newCards.value = drawnCards
        return drawnCards
    }

    // 合成卡片
    const synthesizeCard = (fromCards, targetCard) => {
        const config = cardConfig.cards[targetCard]
        if (!config?.from || config.from.length !== 3) {
            message.error(t('invalidSynthesisTarget'))
            return
        }
        if (!fromCards.every(id => playerData.value.cards.includes(id))) {
            message.error(t('insufficientMaterials'))
            return
        }
        if (playerData.value.cards.length - 3 + 1 > CARD_LIMIT && playerData.value.safeBox.length >= SAFE_BOX_LIMIT) {
            message.error(t('exchangeBoxOverflowSynthesis'))
            return
        }
        fromCards.forEach(id => {
            const index = playerData.value.cards.indexOf(id)
            playerData.value.cards.splice(index, 1)
        })
        addCard(targetCard)
        checkCollectionComplete()
        saveData()
    }

    // 变卡
    const transformCard = (sourceCard, targetCard) => {
        if (!cardConfig.cards[sourceCard] || !cardConfig.cards[targetCard]) {
            message.error(t('cardNotExist'))
            return
        }
        const sourceIndex = playerData.value.cards.indexOf(sourceCard)
        if (sourceIndex === -1) {
            message.error(t('insufficientSourceCard'))
            return
        }
        const sourceValue = cardConfig.cards[sourceCard].value
        const targetValue = cardConfig.cards[targetCard].value
        if (sourceValue < targetValue) {
            message.error(t('insufficientValue'))
            return
        }
        playerData.value.cards.splice(sourceIndex, 1)
        addCard(targetCard)
        saveData()
    }

    // 检测套卡是否已经集齐
    const checkCollectionComplete = () => {
        Object.entries(cardConfig.sets).forEach(([setId, set]) => {
            const cardCounts = {}
            playerData.value.cards.forEach(cardId => {
                cardCounts[cardId] = (cardCounts[cardId] || 0) + 1
            })
            if (set.cards.every(cardId => cardCounts[cardId] >= 1)) {
                set.cards.forEach(cardId => {
                    const index = playerData.value.cards.indexOf(cardId)
                    playerData.value.cards.splice(index, 1)
                })
                playerData.value.collections[setId] = (playerData.value.collections[setId] || 0) + 1
                addLog('setComplete', setId)
                saveData()
            }
        })
    }

    // 卡片市场买卡
    const buyCard = (cardId) => {
        if (!cardConfig.cards[cardId]) {
            message.error(t('cardNotExist'))
            return
        }
        if (playerData.value.gold < 20) {
            message.error(t('insufficientGold'))
            return
        }
        if (!canAddCard()) {
            message.error(t('bothBoxesFull'))
            return
        }
        playerData.value.gold -= 20
        addCard(cardId)
        saveData()
        message.success(t('cardPurchased', {card: cardConfig.cards[cardId]?.name || cardId}))
    }

    // 卡片市场交换卡片
    const exchangeCard = (playerCards, marketCard) => {
        return new Promise((resolve, reject) => {
            if (!cardConfig.cards[marketCard]) {
                reject(new Error(t('marketCardNotExist')))
                return
            }
            const marketValue = cardConfig.cards[marketCard].value
            const invalidCards = playerCards.filter(card =>
                !cardConfig.cards[card] || cardConfig.cards[card].value !== marketValue
            )
            if (invalidCards.length > 0) {
                reject(new Error(t('onlySameValueExchange')))
                return
            }
            const missingCards = playerCards.filter(card => !playerData.value.cards.includes(card))
            if (missingCards.length > 0) {
                reject(new Error(t('insufficientExchangeCards')))
                return
            }
            const exchangeCount = playerCards.length
            const freeSlots = (CARD_LIMIT - playerData.value.cards.length) + (SAFE_BOX_LIMIT - playerData.value.safeBox.length)
            if (freeSlots < exchangeCount) {
                reject(new Error(t('bothBoxesFull')))
                return
            }
            playerCards.forEach(card => {
                const index = playerData.value.cards.indexOf(card)
                playerData.value.cards.splice(index, 1)
            })
            for (let i = 0; i < exchangeCount; i++) {
                addCard(marketCard)
            }
            saveData()
            message.success(t('exchangeSuccess', {count: exchangeCount}))
            resolve()
        })
    }

    // 移动卡片到保险箱
    const moveToSafeBox = (cardId) => {
        return new Promise((resolve, reject) => {
            if (playerData.value.safeBox.length >= SAFE_BOX_LIMIT) {
                message.error(t('safeBoxFull'))
                reject(new Error('Safe box full'))
                return
            }
            const index = playerData.value.cards.indexOf(cardId)
            if (index !== -1) {
                playerData.value.cards.splice(index, 1)
                playerData.value.safeBox.push(cardId)
                saveData()
                message.success(t('movedToSafeBox', {card: cardConfig.cards[cardId]?.name || cardId}))
                resolve()
            } else {
                reject(new Error('Card not found'))
            }
        })
    }

    // 移动卡片到换卡箱
    const moveToExchangeBox = (cardId) => {
        return new Promise((resolve, reject) => {
            if (playerData.value.cards.length >= CARD_LIMIT) {
                message.error(t('exchangeBoxFull'))
                reject(new Error('Exchange box full'))
                return
            }
            const index = playerData.value.safeBox.indexOf(cardId)
            if (index !== -1) {
                playerData.value.safeBox.splice(index, 1)
                playerData.value.cards.push(cardId)
                saveData()
                message.success(t('movedToExchangeBox', {card: cardConfig.cards[cardId]?.name || cardId}))
                resolve()
            } else {
                reject(new Error('Card not found'))
            }
        })
    }

    // 出售卡片
    const sellCard = (cardId) => {
        const index = playerData.value.cards.indexOf(cardId)
        if (index === -1) {
            message.error(t('cardNotInExchangeBox'))
            return
        }
        const value = cardConfig.cards[cardId]?.value || 0
        playerData.value.cards.splice(index, 1)
        playerData.value.gold += value
        saveData()
        message.success(t('cardSold', {card: cardConfig.cards[cardId]?.name || cardId, gold: value}))
    }

    // 刷新市场
    const refreshMarket = () => {
        const commonLowValueCards = Object.entries(cardConfig.cards)
            .filter(([_, card]) => card.value === 10 && !card.isRare)
            .map(([id, card]) => ({id, ...card}))
        marketCards.value = commonLowValueCards
            .sort(() => Math.random() - 0.5)
            .slice(0, 5)
    }

    // 随机一张卡片
    const getRandomCard = () => {
        const cards = Object.keys(cardConfig.cards)
        if (cards.length === 0) {
            console.error('卡片配置为空，请检查 cards.json')
            return null
        }
        return cards[Math.floor(Math.random() * cards.length)]
    }

    return {
        playerData,
        marketCards,
        newCard,
        newCards,
        loadData,
        saveData,
        exportData,
        importData,
        drawCard,
        drawMultipleCards,
        synthesizeCard,
        transformCard,
        buyCard,
        exchangeCard,
        moveToSafeBox,
        moveToExchangeBox,
        sellCard,
        refreshMarket
    }
})